package com.example.cloudreveapp;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.example.cloudreveapp.common.Common;
import com.example.cloudreveapp.databinding.ActivityMainBinding;
import com.example.cloudreveapp.task.fileSyncTask;
import com.example.cloudreveapp.ui.dialog.loadingDialog;
import com.example.cloudreveapp.ui.home.HomeFragment;
import com.example.cloudreveapp.ui.login.LoginAndSetting;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.leon.lfilepickerlibrary.LFilePicker;


import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.URLUtil;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.String;


public class MainActivity extends AppCompatActivity {
    private SharedViewModel viewModel;

    private ActivityMainBinding binding;
    private WebView webView;

    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private final static int FILE_CHOOSER_RESULT_CODE = 10000;
    private FragmentManager manager;

    //加载顶部菜单按钮
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // 使用菜单填充器来将XML文件加载到菜单对象中
        getMenuInflater().inflate(R.menu.top_menu, menu); // 假设您的菜单文件名为 top_menu.xml
        return true;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        }


//        if (requestCode==     FilePickerManager.REQUEST_CODE){
//            if (resultCode == Activity.RESULT_OK) {
//                ArrayList<String> list = (ArrayList<String>) FilePickerManager.obtainData();
//                // do your work
//                for (String file : list) {
//                    Log.e("filePath", "select filePath is " + file + "  *" + file.toString());
//                }
//            } else {
//
//            }
//        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }


    @RequiresApi(api = Build.VERSION_CODES.S)
    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Common.init();

        Common.handler = this.handler;
//        manager = getSupportFragmentManager();
//        /*
//         * 这里为什么要进行空判断，因为在屏幕旋转的时候，系统会执行onSaveInstanceState
//         * 方法去保存当前activity的状态，然后activity会重建，执行onCreate方法，如果我们不判断
//         * savedInstanceState是否为空，那么每次就会执行下面的commit操作，向Fragmnet传递参数，
//         * 这样参数的却会保留下来，但是我们不应该每次都去传递参数。当进行了空判断时，当Activity重建
//         * 的时候，会调用Fragment的默认构造函数，所以我们传递过去的参数不能保留了。
//         */
//        if(savedInstanceState == null){
//            manager.beginTransaction().replace(R.id.fl_main, new FragmentOne("params")).commit();
//        }


        int PERMISSION_REQUEST = 1;

        if (ActivityCompat.checkSelfPermission(this,
                android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            String[] PERMISSIONS = {android.Manifest.permission.READ_EXTERNAL_STORAGE};
            ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_REQUEST);
        }

        if (!Common.isLoginTag) {

            // todo set cookies
            Log.i("TAG", "------------------------info first in");
            Intent intent = new Intent(this, LoginAndSetting.class);
            startActivity(intent);
            return;
        }

        loadingDialog a = new loadingDialog(this);
        a.show();
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(1100);
                    a.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();

        Toast.makeText(getApplicationContext(), "欢迎使用网盘APP", Toast.LENGTH_SHORT).show();


        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 初始化WebView
        webView = binding.webview; // 假设你的ActivityMainBinding中有名为webView的WebView
        webView.setWebViewClient(webViewClient);
        webView.setWebChromeClient(webChromeClient);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);


        // 底部导航
        BottomNavigationView navView = findViewById(R.id.nav_view);
        webView = findViewById(R.id.webview); // 替换以匹配您的WebView ID

        // 您的NavController
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
        // 设置自定义的监听器
        navView.setOnItemSelectedListener(item -> {
            viewModel = new ViewModelProvider(this).get(SharedViewModel.class);
            String storedHostAddress = getStoredHostAddress();
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    // 在这里处理"首页"逻辑
                    //
//                    navController.navigate(R.id.navigation_home);
                    viewModel.setUrlToLoad(storedHostAddress);
                    return true;
                case R.id.navigation_settings:
                    // 直接在WebView中加载"设置"的网页
                    // 获取存储的主机地址，构建URL

                    String settingsUrl = storedHostAddress + "/setting";

                    viewModel.setUrlToLoad(settingsUrl);
                    //Toast.makeText(getApplicationContext(), settingsUrl, Toast.LENGTH_SHORT).show();
                    return true;
                case R.id.navigation_about:
                    showAboutDialog();
                    return true;
                case R.id.action_logout:
//                    Toast.makeText(getApplicationContext(), "退出按钮测试", Toast.LENGTH_SHORT).show();
                    return true;
                // 如果有其他菜单项，可以继续添加case
                default:
                    return false;
            }
        });

        // 确保WebView不为null
        if (webView == null) {
            webView = new WebView(this);
            // 添加WebView到布局如果必要的话
        }

        //不需要原来的导航
//        BottomNavigationView navView = findViewById(R.id.nav_view);
//        // Passing each menu ID as a set of Ids because each
//        // menu should be considered as top level destinations.
//        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
//                R.id.navigation_home, R.id.navigation_settings)
//                .build();
//        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
//        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
//        NavigationUI.setupWithNavController(binding.navView, navController);


    }

    public void logout() {
        // 清除SharedPreferences中的数据
//        SharedPreferences sp = getSharedPreferences(Common.LocalStorageName, MODE_PRIVATE);
//        sp.edit().remove(Common.CONST_USER_NAME).remove(Common.CONST_USER_PWD).apply();
//
//        // 更新Common中的变量状态
//        Common.isLoginTag = false;
        // 清除SharedPreferences中的数据
        SharedPreferences sp = getSharedPreferences(Common.LocalStorageName, MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(Common.CONST_HOST);
        editor.remove(Common.CONST_USER_NAME);
        editor.remove(Common.CONST_USER_PWD);
        editor.apply();

        // 如果使用 Common.isLoginTag 来记录登录状态，确保也重置此状态
        Common.isLoginTag = false;

        // 重定向到登录页面
        Intent intent = new Intent(this, LoginAndSetting.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
        Toast.makeText(getApplicationContext(), "已退出并清除记录", Toast.LENGTH_SHORT).show();
    }
    // 如果是菜单项
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_logout) {
            logout(); // 调用上面定义的logout方法
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private String getStoredHostAddress() {
        SharedPreferences sp = getSharedPreferences(Common.LocalStorageName, MODE_PRIVATE);
        // 如果不确定host是否以http开始，可能还需要做一些处理
        return sp.getString(Common.CONST_HOST, "default_host");
    }

    private void showAboutDialog() {
        // 创建一个 AlertDialog 构建器
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        // 获取布局填充器
        LayoutInflater inflater = getLayoutInflater();
        // 填充并设置自定义的布局
        builder.setView(inflater.inflate(R.layout.dialog_about, null));
        // 创建AlertDialog
        AlertDialog dialog = builder.create();
        // 显示Dialog
        dialog.show();
    }
    /**
     * 使用系统的下载服务
     *
     * @param url                下载地址
     * @param contentDisposition attachment;filename=测试专用.wps;filename*=utf-8''测试专用.wps
     * @param mimeType           application/octet-stream
     */
    private void downloadBySystem(String url, String contentDisposition, String mimeType) {
        Log.d("TAG", "downloadBySystem：url=" + url + "，contentDisposition="
                + contentDisposition + "，mimeType=" + mimeType);
        // 指定下载地址
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        // 允许媒体扫描，根据下载的文件类型被加入相册、音乐等媒体库
        request.allowScanningByMediaScanner();
        // 设置通知的显示类型，下载进行时和完成后显示通知
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        // 设置通知栏的标题，如果不设置，默认使用文件名
        // request.setTitle("This is title");
        // 设置通知栏的描述
        // request.setDescription("This is description");
        // 允许在计费流量下下载
        request.setAllowedOverMetered(false);
        // 允许该记录在下载管理界面可见
        request.setVisibleInDownloadsUi(false);
        // 允许漫游时下载
        request.setAllowedOverRoaming(true);
        // 允许下载的网路类型
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        // 设置下载文件保存的路径和文件名
        String fileName = URLUtil.guessFileName(url, contentDisposition, mimeType);
        Log.d("TAG", "fileName：" + fileName);

        //storage/emulated/0/Android/data/项目名/files
        // request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
        // request.setDestinationInExternalPublicDir(ConstantPath.getCommonPath(mContext), fileName);

        //Android/data/项目名/files/storage/emulated/0/Android/data/项目名/files
        // request.setDestinationInExternalFilesDir(this, ConstantPath.getCommonPath(mContext), fileName);

//        //另外可选一下方法，自定义下载路径
//        Uri mDestinationUri = Uri.withAppendedPath(Uri.fromFile(
//                new File(ConstantPath.getRootPath(ConstantPath.ANDROIDMOBILE))), fileName);
//        // Uri mDestinationUri = Uri.withAppendedPath(Uri.fromFile(
//        //                new File(ConstantPath.getCommonPath(mContext))), fileName);
//        request.setDestinationUri(mDestinationUri);

        final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        // 添加一个下载任务
        long downloadId = downloadManager.enqueue(request);
        Log.d("TAG", "downloadId：" + downloadId);
    }

    //WebViewClient主要帮助WebView处理各种通知、请求事件
    private WebViewClient webViewClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {//页面加载完成
            //progressBar.setVisibility(View.GONE);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载
            // progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.i("ansen", "load url:" + url);
            return super.shouldOverrideUrlLoading(view, url);
        }

    };


    //WebChromeClient主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等
    private WebChromeClient webChromeClient = new WebChromeClient() {
        //不支持js的alert弹窗，需要自己监听然后通过dialog弹窗
        @Override
        public boolean onJsAlert(WebView webView, String url, String message, JsResult result) {
            AlertDialog.Builder localBuilder = new AlertDialog.Builder(webView.getContext());
            localBuilder.setMessage(message).setPositiveButton("确定", null);
            localBuilder.setCancelable(false);
            localBuilder.create().show();

            //注意:
            //必须要这一句代码:result.confirm()表示:
            //处理结果为确定状态同时唤醒WebCore线程
            //否则不能继续点击按钮
            result.confirm();
            return true;
        }

        //获取网页标题
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            Log.i("ansen", "网页标题:" + title);
        }

        //加载进度回调
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            // progressBar.setProgress(newProgress);

        }

    };

    @SuppressLint("HandlerLeak")
    private final Handler handler = new Handler() {

        public void handleMessage(Message msg) {
            String str = (String) msg.obj;
            Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
        };
    };


}

